﻿/**
 * Dom相关方法
 * @namespace Dom
 * @name core.Dom
 * @static
 */
core.Dom = {};
(function () {
  /**
   * 页面dom节点加载完毕时调用指定的回调函数
   * @name core.Dom.ready
   * @function
   * @grammar core.Dom.ready(callback)
   * @param {Function} callback 页面加载完毕时调用的函数.
   * @remark 如果有条件将js放在页面最底部, 也能达到同样效果，不必使用该方法
   */
  var ready = core.Dom.ready = function () {
    var readyBound = false,
      readyList = [],
      DOMContentLoaded;
    if (document.addEventListener) {
      DOMContentLoaded = function () {
        document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);
        ready();
      };
    } else if (document.attachEvent) {
      DOMContentLoaded = function () {
        if (document.readyState === 'complete') {
          document.detachEvent('onreadystatechange', DOMContentLoaded);
          ready();
        }
      };
    }

    function ready() {
      if (!ready.isReady) {
        ready.isReady = true;
        for (var i = 0, j = readyList.length; i < j; i++) {
          readyList[i]();
        }
      }
    }

    function doScrollCheck() {
      try {
        document.documentElement.doScroll("left");
      } catch (e) {
        setTimeout(doScrollCheck, 1);
        return;
      }
      ready();
    }

    function bindReady() {
      if (readyBound) {
        return;
      }
      readyBound = true;
      if (document.readyState === 'complete') {
        ready.isReady = true;
      } else {
        if (document.addEventListener) {
          document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
          window.addEventListener('load', ready, false);
        } else if (document.attachEvent) {
          document.attachEvent('onreadystatechange', DOMContentLoaded);
          window.attachEvent('onload', ready);
          var toplevel = false;
          try {
            toplevel = window.frameElement == null;
          } catch (e) {
          }
          if (document.documentElement.doScroll && toplevel) {
            doScrollCheck();
          }
        }
      }
    }

    bindReady();
    return function (callback) {
      ready.isReady ? callback() : readyList.push(callback);
    };
  }();
  ready.isReady = false;
})();
core.Dom.hasClass = function (obj, cls) {
  return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
core.Dom.addClass = function (obj, cls) {
  if (!this.hasClass(obj, cls)) obj.className += " " + cls;
  return this;
};
core.Dom.removeClass = function (obj, cls) {
  if (this.hasClass(obj, cls)) {
    var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
    obj.className = obj.className.replace(reg, ' ');
  }
  return this;
};
